/*
 * autor: Marcin Formela
*/
package pl.formit04.mail;

import java.io.IOException; 
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties; 
import java.util.Date;
import java.util.Iterator;

import javax.servlet.http.*;

import javax.activation.DataHandler;

import javax.mail.BodyPart;
import javax.mail.Session; 
import javax.mail.internet.MimeMessage; 
import javax.mail.internet.MimeMultipart;
import javax.mail.Address;
import javax.mail.Transport;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Extent;
import javax.jdo.Query;

import com.google.appengine.api.datastore.Text;
import pl.formit04.mail.PMF;


@SuppressWarnings("serial")
public class MailHandlerServlet extends HttpServlet 
{
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException 
	{
		resp.setContentType("text/plain");
		resp.getWriter().println("Data Creation");
		String call = new String(req.getParameter(new String("param")));
		PersistenceManager pm = PMF.get().getPersistenceManager();
		if(call.equals("cron")){
			Properties props = new Properties(); 
			Session session = Session.getDefaultInstance(props, null); 
			
            try
            {  
            	Query queryOwner = pm.newQuery(ClientStore.class);
            	queryOwner.setFilter("sent == :sentParam");

                List<ClientStore> results = (List<ClientStore>) queryOwner.execute(false);
            	
            	for(ClientStore clientStore : results)
            	{
	                try
	                {
	                	Message msg = new MimeMessage(session);
		            	msg.setFrom(new InternetAddress("noreply@formit04.appspotmail.com", "kontakt Modulook.pl [NO-REPLY]"));
		                msg.addRecipient(Message.RecipientType.TO,
		                                 new InternetAddress(clientStore.getOwner(), clientStore.getOwner()));
		                List<String> listCc = EmailStore.getCC(pm,clientStore.getOwner());
		               
		                for(String ccMail : listCc)
		                {
		                	msg.addRecipient(Message.RecipientType.CC, new InternetAddress(ccMail, ccMail));
		                }
		                msg.addRecipient(Message.RecipientType.CC, new InternetAddress("modulook@modulook.pl", "Biuro Modulook - tylko DW"));
		                msg.addRecipient(Message.RecipientType.BCC, new InternetAddress("marcin@formela.pl", "Admin"));
		                Address[] reply = {new InternetAddress("marcin@formela.pl", "Admin")};
						msg.setReplyTo(reply);
		                msg.setSubject( clientStore.getName() );
		                String msgBody = clientStore.getDate() + " + 1h" + "\n Osoba odpowiedzialna za kontakt: " 
		                										+ clientStore.getOwner() + "\n" +  clientStore.getComent().getValue();
		                msg.setText(msgBody);
		             //   System.out.println(msgBody.toString());
		                Transport.send(msg);
		            	clientStore.setSent(true);
		            	Thread.sleep(15000);
		            	
	                }
	                catch(Exception excep)
	                {
	                	pm.makePersistent(clientStore);	
		            	pm.flush();
	                	System.out.println(excep.getMessage());
	                } 
            	}	
            }
            finally
        	{
            	pm.close();
        	}
            
		}
		if(call.equals("create"))
		{
			resp.getWriter().println("create started");	
			EmailStore es1 = new EmailStore("marcin@formela.pl", 0);
			EmailStore es2 = new EmailStore("marcin1@formela.pl", 1);
			EmailStore es3 = new EmailStore("marcin2@formela.pl", 2);
			EmailStore es4 = new EmailStore("marcin3@formela.pl", 3);
			EmailStore es5 = new EmailStore("admin4@formela.pl", 4);
			EmailStore es6 = new EmailStore("admin5@formela.pl", 5);
			IdStore is1 = new IdStore("user", 1);
			IdStore is2 = new IdStore("client", 1);
			try
	        {
//	        	pm.makePersistent(es1);  
//	        	pm.makePersistent(es2);
//	        	pm.makePersistent(es3);
//	        	pm.makePersistent(es4);
//	        	pm.makePersistent(es5);
//	        	pm.makePersistent(es6);
//	        	pm.makePersistent(is1);
//	        	pm.makePersistent(is2);
	        	resp.getWriter().println("create done");
	        }
	        catch(Exception e)
	        {
	        	resp.getWriter().println("create error");
	        	System.out.println(e.getMessage());
	        }
	        finally {
	            pm.close();
	        }    
		}
		
		if(call.equals("view"))
		{
			
			resp.getWriter().println("view");
			//view emails
			Extent<EmailStore> extent = pm.getExtent(EmailStore.class, false);
			for (Iterator<EmailStore> i = extent.iterator(); i.hasNext();)
			{
				EmailStore es = i.next();
				resp.getWriter().println("id:" + es.getIdSeq() +
										" mail:" + es.getEmail());
			}				
			extent.closeAll();
			
			//view clients
			Extent<ClientStore> extent2 = pm.getExtent(ClientStore.class, false);
			
			for (Iterator<ClientStore> i = extent2.iterator(); i.hasNext();)
			{
				ClientStore cs = i.next();
				
				resp.getWriter().println(cs.toString());
				
			}						
			extent2.closeAll();	
			//view ids
			Extent<IdStore> extent3 = pm.getExtent(IdStore.class, false);

			for (Iterator<IdStore> i = extent3.iterator(); i.hasNext();)
			{
				IdStore is = i.next();
				resp.getWriter().println("name: " + is.getSeqName() + " seq: " + is.getSeqNumberNoIncrease());
			}				
			extent3.closeAll();
		}
		

			
	}
	public void doPost(HttpServletRequest req, HttpServletResponse resp)throws IOException 
	{	
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try 
		{
			Properties props = new Properties(); 
	        Session session = Session.getDefaultInstance(props, null); 
	        MimeMessage message = new MimeMessage(session, req.getInputStream());
	        DataHandler dh = message.getDataHandler();
	        
	        //web
//	        ClientStore clientStore = new ClientStore(pm,
//	        										message.getSubject().toString(),
//	        										(message.getFrom())[0].toString(),
//	        										new Date(),
//	        										new Text( (String) (dh.getContent())));
//            
	        
	        //local
	        MimeMultipart mm = (MimeMultipart)dh.getContent();
	        BodyPart bp = mm.getBodyPart(0);
	        ClientStore clientStore = new ClientStore(pm,
					message.getSubject().toString(),
					(message.getFrom())[0].toString(),
					new Date(),
					new Text( (String) (bp.getContent())));
	        
	        
	        
	        

	        pm.makePersistent(clientStore);
	        pm.flush();
	        
	        
//	        Message msg = new MimeMessage(session);
//            msg.setFrom(new InternetAddress("formularz@formit04.appspotmail.com", "kontakt Modulook.pl"));
//            msg.addRecipient(Message.RecipientType.TO,
//                             new InternetAddress(clientStore.getOwner(), clientStore.getOwner()));
//            List<String> listCc = EmailStore.getCC(pm,clientStore.getOwner());
//           
//            for(String ccMail : listCc)
//            {
//            	msg.addRecipient(Message.RecipientType.CC, new InternetAddress(ccMail, ccMail));
//            }
//            
// 
//            msg.setSubject( clientStore.getName() );
//            String msgBody = clientStore.getDate() + " + 1h" + "\n Osoba odpowiedzialna za kontakt: " 
//            										+ clientStore.getOwner() + "\n" +  clientStore.getComent().getValue();
//            msg.setText(msgBody);
//            
//            Transport.send(msg);
//        	clientStore.setSent(true);
//        	pm.makePersistent(clientStore);	
		    

		}
		catch(Exception e)
		{
			System.out.println("error: " + e.toString());
		}
		finally 
		{
            pm.close();
        }
	}
}
